<!--
 * @Author: early-autumn
 * @Date: 2020-05-08 11:21:14
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 15:39:21
 -->
<template>
  <div style="overflow: hidden">
    <el-tabs class="Tabs" type="border-card" style="margin: 15px">
      <el-tab-pane label="预约视图">
        <appointment-time
          v-if="mountedDisplay"
          :loading="loading"
          :resources="resources"
          :events="events"
          @date-change="handleDateChange"
          @event-change="handleEventChange"
          @event-click="handleAppointmentPatient"
          @refresh="handleRequest"
          @add="handleAdd"
          @dates-render="datesRender"
          @events-render="eventsRender"
        ></appointment-time>
        <appointment-panel
          v-if="mountedDisplay"
          v-model="appointmentPanelVisible"
          :default-data="appointmentPanelData"
          :default-patient="appointmentPanelPatient"
          @submit="getListAppointment"
        ></appointment-panel>
        <appointment-patient
          v-if="mountedDisplay"
          v-model="appointmentPatientVisible"
          :data.sync="appointmentPatientData"
          @update="getListAppointment"
          @appointment-update="handleAppointmentPanelVisible"
          @appointment-again="handleAppointmentPanelVisible"
        ></appointment-patient>
      </el-tab-pane>
    </el-tabs>
    <footer-box></footer-box>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { listStaff } from '@/api/services/common'
import { listPlan } from '@/api/services/plan'
import { listAppointment, updateAppointment } from '@/api/services/appointment'
import { getThisWeekStartWithEnd, getTodayStartWithEnd } from '@/utils/date'
import { appointmentColorEnum } from '@/utils/enums'

import AppointmentTime from './AppointmentTime'
import AppointmentPanel from './AppointmentPanel'
import AppointmentPatient from './AppointmentPatient'
import FooterBox from '@/components/yiya/FooterBox'

export default {
  name: 'ShopAppointment',
  components: {
    AppointmentTime,
    AppointmentPanel,
    AppointmentPatient,
    FooterBox,
  },
  data() {
    return {
      loading: false,
      doctorList: [],
      restMap: {},
      appointmentList: [],
      currentDate: getTodayStartWithEnd(),
      appointmentPanelVisible: false,
      appointmentPanelData: {},
      appointmentPanelPatient: undefined,
      appointmentPatientVisible: false,
      appointmentPatientData: {},
      mountedDisplay: false,
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    resources() {
      const [start, end] = this.currentDate
      const startDate = dayjs(start).format('YYYY-MM-DD')
      const endDate = dayjs(end).format('YYYY-MM-DD')
      return Object.entries(this.restMap)
        .filter(([date]) => date >= startDate && date <= endDate)
        .map(([date, rests]) =>
          this.doctorList
            .filter((doctor) => !rests[doctor.userId])
            .map((doctor) => ({
              id: doctor.userId,
              date,
              title: doctor.userName,
              doctor,
            }))
        )
        .flat()
    },
    events() {
      return this.appointmentList
        .filter((a) => a.appointmentStatus !== 8 && a.appointmentStatus !== 6)
        .map((appointment) => ({
          id: appointment.id,
          title: appointment.clinicPersonName,
          resourceId: appointment.doctorId,
          start: appointment.startReservationTime,
          end: appointment.endReservationTime,
          data: appointment,
          backgroundColor: appointmentColorEnum[appointment.appointmentStatus],
        }))
    },
  },
  async mounted() {
    await this.getListStaff()
    this.mountedDisplay = true
  },
  methods: {
    async getListStaff() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: '医生-洁牙师',
      })
      this.doctorList = data
    },
    async getListPlan() {
      const [start, end] = this.currentDate
      const beginTime = dayjs(start).format('YYYY-MM-DD')
      const endTime = dayjs(end).format('YYYY-MM-DD')
      const { rows } = await listPlan({
        beginTime,
        endTime,
        clinicId: +this.clinicId,
      })
      const map = {}
      let currentTime = beginTime
      while (currentTime <= endTime) {
        map[currentTime] = {}
        currentTime = dayjs(currentTime).add(1, 'day').format('YYYY-MM-DD')
      }
      rows.forEach((rest) => (map[rest.time][rest.userId] = true))
      this.restMap = map
    },
    async getListAppointment() {
      const [start, end] = this.currentDate
      const beginTime = dayjs(start).format('YYYY-MM-DD')
      const endTime = dayjs(end).format('YYYY-MM-DD')
      const { rows } = await listAppointment({
        beginTime,
        endTime,
        clinicId: +this.clinicId,
      })
      this.appointmentList = rows.map((item) => ({
        ...item,
        appointmentStatus:
          item.appointmentStatus === 0 ? 1 : item.appointmentStatus,
      }))
    },
    handleDateChange(type, date) {
      this.currentDate =
        type === 'date'
          ? getTodayStartWithEnd(date)
          : getThisWeekStartWithEnd(date)
      this.handleRequest()
    },
    async handleRequest() {
      try {
        this.loading = true
        await this.getListPlan()
        await this.getListAppointment()
      } finally {
        this.loading = false
      }
    },
    async handleEventChange(e) {
      try {
        const { newResource, event } = e
        const { start, end } = event
        await this.$confirm('修改预约信息, 是否继续?', { type: 'warning' })
        const params = {
          id: +event.id,
          reservationDate: dayjs(start).format('YYYY-MM-DD'),
          startReservationTime: dayjs(start).format('YYYY-MM-DD HH:mm:ss'),
          endReservationTime: dayjs(end).format('YYYY-MM-DD HH:mm:ss'),
        }
        if (newResource) {
          params.doctorId = +newResource.id
          params.doctorName = newResource.title
        }
        await updateAppointment(params)
        await this.getListAppointment()
      } catch (err) {
        e.revert()
      }
    },
    handleAppointmentPanelVisible(data, patient) {
      this.appointmentPanelData = data
      this.appointmentPanelPatient = patient
      this.appointmentPanelVisible = true
    },
    handleAdd(e) {
      const { start, end, resource } = e
      const { date, doctor } = resource.extendedProps
      const { userId, userName } = doctor
      this.handleAppointmentPanelVisible({
        doctorId: +userId,
        doctorName: userName,
        reservationDate: date,
        startReservationTime: start,
        endReservationTime: end,
      })
    },
    handleAppointmentPatient(e) {
      this.appointmentPatientData = e.event.extendedProps.data
      this.appointmentPatientVisible = true
    },
    datesRender(e) {
      if (e.view.type == 'resourceTimeGridDay') {
        //如果是日视图
        let now = new Date()
        let str = now.getHours() + ':' + now.getMinutes() + now.getSeconds()
        let currentTime = Number(str.replace(/:/g, ''))
        let colNum = -1
        let elObjs = document
          .getElementsByClassName('fc-time-grid')[0]
          .getElementsByTagName('tr')
        for (let i = 1; i < elObjs.length - 1; i++) {
          if (
            currentTime <=
            Number(elObjs[i].getAttribute('data-time').replace(/:/g, ''))
          ) {
            colNum = i
            break
          }
        }
        if (colNum > 1) {
          elObjs[colNum - 1].style.backgroundColor = '#e5e5e5'
        }
      }
    },
    eventsRender(dataObj) {
      //添加备注信息
      let dv = document.createElement('div') //创建段落节点
      let txt = document.createTextNode(
        dataObj.event.extendedProps.data.remarks
      )
      dv.appendChild(txt)
      dv.style.marginTop = '10px'
      dataObj.el.childNodes[0].appendChild(dv)
    },
  },
}
</script>

<style lang="scss" scoped>
.Tabs >>> .el-tabs__content {
  padding: 0 15px;
}
</style>
